package com.briup.day27;

import com.briup.day27.bean.Student;

import java.lang.reflect.Constructor;

public class Test_Constructor {
    public static void main(String[] args) throws Exception {
        Class<?> clazz  = Class.forName("com.briup.day27.bean.Student");
        //获取指定的构造器 通过指定的构造器实例化对象
        Constructor<?> c1 = clazz.getConstructor(String.class, String.class,int.class);
        //实例化对象
        Student s = (Student) c1.newInstance("001", "terry", 10);
        System.out.println(s);
        System.out.println("----------------");
//        Student s1=new Student("2");//Student(java.lang.String)' 在 'com.briup.day27.bean.Student' 中具有 private 访问权限
//     只能获取Public的   Constructor<?> c2 = clazz.getConstructor(String.class);
        Constructor<?> c2 = clazz.getDeclaredConstructor(String.class);
        //包含private的用上面这个带Declared
        //可以开放私有构造器实例化对象权限
        c2.setAccessible(true);
        Student s2 = (Student) c2.newInstance("001");
        System.out.println(s2);//Student{id='001', name='null', age=0}因为调用了toString才空的
    }
    public static void main02(String[] args) throws Exception {
        //获取指定构造器实例化对象
        Class<?> clazz  = Class.forName("com.briup.day27.bean.Student");
        //获取指定构造器（无参构造器）//不传参数就是获取无参构造器
        Constructor<?> c = clazz.getConstructor();
        //通过指定构造器实例化对象
        //c.newInstance()调用构造器创建新实例
        Student s1 = (Student) c.newInstance();
        System.out.println(s1);
    }
    public static void main01(String[] args) throws ClassNotFoundException {
   /*获取类的字节码对象 使用反射机制基础*/
        Class<?> clazz  = Class.forName("com.briup.day27.bean.Student");
    /*通过字节码对象获取所有public构造方法*/
        Constructor<?>[] c1 =   clazz.getConstructors();
        //类要有java.lang 构造方法不用
        /*public构造方法public com.briup.day27.bean.Student(java.lang.String,java.lang.String,int)
public构造方法public com.briup.day27.bean.Student()*/
        for (Constructor<?> c : c1) {
            System.out.println("public构造方法"+c);
        }
        /*获取所有构造方法*/
        Constructor<?>[] c2 = clazz.getDeclaredConstructors();
        for (Constructor<?> c : c2) {
            System.out.println("所有构造方法"+c);
        }
    }
}
